using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using SapaFinance.DTO;
using SapaFinance.Domain.Model;

namespace SapaFinance.OOMap.Helpers
{
    public class RequestToOrderDTOConvert : TypeConverter<IEnumerable<Request>, OrderDTO>
    {
        protected override OrderDTO ConvertCore(IEnumerable<Request> requests)
        {
            var orderDto = new OrderDTO();
            if (requests != null){
                var oneRequest = requests.First();
                if (oneRequest != null)
                {
                    orderDto.CurrencyName = oneRequest.PayeeAccount.Currency.Name;
                    orderDto.SelectedCurrency = oneRequest.PayeeAccount.Currency.UID;
                    if (oneRequest.Payer != null){
                        orderDto.SelectedAgent = oneRequest.Payer.Agent.UID;
                        orderDto.PayerSharePie = oneRequest.Payer.Name;
                        orderDto.AgentName = oneRequest.Payer.Agent.Name;
                    }
                }

                orderDto.PaymentPeriod = DateTime.Now;
                orderDto.Payment = 0;
                foreach (var amount in requests.Select(request => request.GetNotPaidAmount())) orderDto.Payment += amount.Amount;
                orderDto.PaymentPurpose = string.Join("; ", requests.Select(x => x.PaymentPurpose));
                orderDto.LinkedRequests = requests.Select(x => x.UID).ToArray();
            }
            return orderDto;
        }
    }
}